import "./style.css";

const app = document.querySelector("#app") as HTMLElement;

const hourHand = document.querySelector("#hour") as HTMLElement;
const minuteHand = document.querySelector("#minute") as HTMLElement;
const secondHand = document.querySelector("#second") as HTMLElement;

const handLightColor = ["#ff0000", "#00ff00", "#ffff00"];
[...app.children].forEach((item, index) => {
    (item as HTMLElement).style.setProperty("--color", handLightColor[index]);
});

function formatTime(time: number) {
    return time < 10 ? `0${time}` : `${time}`;
}

function updateTime() {
    const now = new Date();
    const hours = formatTime(now.getHours());
    const minutes = formatTime(now.getMinutes());
    const seconds = formatTime(now.getSeconds());

    // 刻度元素
    // 在当前时刻之前的有 active 类，之后的没有 active 类
    // 旋转角度 +90 度，是将水平的 0 读线竖过来，以 12 点钟方向为 0 度，顺时针转动
    const hourDotEls = Array.from({ length: 24 }, (_, index) => {
        return +hours >= index
            ? `<i class="dot active" style="--deg: ${index * 15 + 90}deg"></i>`
            : `<i class="dot" style="--deg: ${index * 15 + 90}deg"></i>`;
    }).join("");
    const minuteDotEls = Array.from({ length: 60 }, (_, index) => {
        return +minutes >= index
            ? `<i class="dot active" style="--deg: ${index * 6 + 90}deg"></i>`
            : `<i class="dot" style="--deg: ${index * 6 + 90}deg"></i>`;
    }).join("");
    const secondDotEls = Array.from({ length: 60 }, (_, index) => {
        return +seconds >= index
            ? `<i class="dot active" style="--deg: ${index * 6 + 90}deg"></i>`
            : `<i class="dot" style="--deg: ${index * 6 + 90}deg"></i>`;
    }).join("");

    // 指针转动
    // hourHand.style.transform = `rotate(${(hours / i2) * 360 + 90}deg)`;
    // minuteHand.style.transform = `rotate(${(minutes / 60) * 360 + 90}deg)`;
    // secondHand.style.transform = `rotate(${(seconds / 60) * 360 + 90}deg)`;

    // 数字显示
    hourHand.innerHTML = `<div class="dots">${hourDotEls}</div><h2>${hours}</h2><span>HOUR</span>`;
    minuteHand.innerHTML = `<div class="dots">${minuteDotEls}</div><h2>${minutes}</h2><span>MINUTE</span>`;
    secondHand.innerHTML = `<div class="dots">${secondDotEls}</div><h2>${seconds}</h2><span>SECOND</span>`;
}

setInterval(updateTime, 1000);

// 用不着 requestAnimationFrame，时间更新频率很低，没必要频繁执行更新dom
// requestAnimationFrame(function update() {
//     updateTime();
//     requestAnimationFrame(update);
// });
